//
//  ModifyPhotoViewController.m
//  PigMarket
//
//  Created by Felix on 2019/3/19.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "ModifyPhotoViewController.h"

#import "ModifyPhotoFlowLayout.h"
#import "ModifyPhotoCell.h"
#import "TZImagePickerController.h"
#import "PhotoDataProvider.h"

#define ANGLE_TO_RADIAN(angle) ((angle)/180.0* M_PI)
#define MaxPhotoCount 6

@interface ModifyPhotoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,TZImagePickerControllerDelegate>

/**
 topView
 */
@property (nonatomic , strong) UIView *topView;

/**
 tips
 */
@property (nonatomic , strong) UILabel *tips;

/**
 提交btn
 */
@property (nonatomic, strong) UIButton *commitBtn;
/**
 photoCollectionView
 */
@property (nonatomic , strong) UICollectionView *photoCollectionView;

/**
 flowLayout
 */
@property (nonatomic , strong) ModifyPhotoFlowLayout *flowLayout;

/**
 currentPhotos
 */
@property (nonatomic , strong) NSMutableArray *currentPhotos;

/**
 currentAssets
 */
@property (nonatomic , strong) NSMutableArray *currentAssets;


/**
 是否选择原图
 */
@property (nonatomic, assign) BOOL isSelectOriginalPhoto;


/**
 长按手势
 */
@property (nonatomic , strong) UILongPressGestureRecognizer *longPressGestureRecognizer;


/**
 上传图片imgNamearr
 */
@property (nonatomic , strong) NSMutableArray *uploadImgsNameArr;



@end



@implementation ModifyPhotoViewController


#pragma mark - view life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.baseNavView.navTitleLabel.text = @"常用照片";
    [self setUpNavRightUploadBtn];
    [self setUpView];
}


#pragma mark - init method
- (void)setUpNavRightUploadBtn {
    
    self.baseNavView.rightNavBtn.hidden = NO;
    [self.baseNavView.rightNavBtn setTitle:@"提交" forState:UIControlStateNormal];

    @weakify(self);
    self.baseNavView.rightBlock = ^{
        @strongify(self);
        [self uploadPhotosWithPhotos];
    };
    
}

- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}

- (void)initView {
    [self.view addSubview:self.topView];
    [self.topView addSubview:self.tips];
    [self.view addSubview:self.photoCollectionView];
}

- (void) initLayout {
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(TJ_NavBarHeight);
        make.height.mas_equalTo(34);
    }];
    [self.tips mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.centerY.mas_equalTo(0);
    }];
    [self.photoCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topView.mas_bottom);
        make.left.right.bottom.mas_equalTo(0);
    }];
}


- (void) initAction {
    self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureTapped:)];
    [self.photoCollectionView addGestureRecognizer:self.longPressGestureRecognizer];
}

- (void)initData {

    if ([PhotoDataProvider sharedInstance].currentPhotos && [PhotoDataProvider sharedInstance].currentAssets) {
        self.currentPhotos = [PhotoDataProvider sharedInstance].currentPhotos;
        self.currentAssets = [PhotoDataProvider sharedInstance].currentAssets;
    }
}



#pragma mark - delegate
#pragma mark UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSUInteger count = self.dataArr.count + self.currentPhotos.count;
    if (count >= MaxPhotoCount) {
        return count;
    }
    return count + 1;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ModifyPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ModifyPhotoCellID" forIndexPath:indexPath];
    NSUInteger count = self.dataArr.count + self.currentPhotos.count;
    if (indexPath.item == count) {
        cell.imageView.image = [UIImage imageNamed:@"user_modifyphoto_add"];
        cell.deleteBtn.hidden = YES;
    } else {
        if (self.dataArr.count > indexPath.item) {
            Photos *model = self.dataArr[indexPath.item];
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.url] placeholderImage:[UIImage imageNamed:@"placeholder_small"]];
        } else {
            
            NSInteger index = indexPath.item - (self.dataArr.count);
            cell.imageView.image = self.currentPhotos[index];
        }
        cell.deleteBtn.hidden = YES;
    }
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger count = self.dataArr.count + self.currentPhotos.count;
    if (indexPath.item == count) {
        @weakify(self);
        [[AlertAction sharedInstance] showAlertSheetWithTitle:nil message:nil itemsArr:@[@"拍照",@"相册选择"] selectItemBlock:^(NSString *selectItem) {
            @strongify(self);
            if ([selectItem isEqualToString:@"拍照"]) {
                [self takePhoto];
            } else if ([selectItem isEqualToString:@"相册选择"]) {
                [self photoAlbum];
            }
        }];
 
    } else {
        ModifyPhotoCell *cell = (ModifyPhotoCell *)[self.photoCollectionView cellForItemAtIndexPath:indexPath];
        if (cell.isShaking) {
            cell.isShaking = NO;
            cell.deleteBtn.hidden = YES;
            [self endShake:cell];
        } else {
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:self.currentAssets selectedPhotos:self.currentPhotos index:indexPath.item];
            imagePickerVc.maxImagesCount = MaxPhotoCount;
            imagePickerVc.isSelectOriginalPhoto = self.isSelectOriginalPhoto;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                self->_currentPhotos = [NSMutableArray arrayWithArray:photos];
                self->_currentAssets = [NSMutableArray arrayWithArray:assets];
                self->_isSelectOriginalPhoto = isSelectOriginalPhoto;
                [self->_photoCollectionView reloadData];
            }];
            [self presentViewController:imagePickerVc animated:YES completion:nil];
        }
    }
}


#pragma mark TZImagePickerControllerDelegate
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    [self.currentPhotos removeAllObjects];
    [self.currentAssets removeAllObjects];
    
    [self.currentPhotos addObjectsFromArray:photos];
    [self.currentAssets addObjectsFromArray:assets];


    self.isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_photoCollectionView reloadData];
}


#pragma mark - target action

- (void)deleteBtnTapped:(UIButton *)btn {
    [self deletePhotoRequestWithBtn:btn];
}

- (void) deletePhotoRequestWithBtn:(UIButton *)btn {
    
    NSInteger index = self.dataArr.count;
    
    if (index >btn.tag) {
        
        Photos *photoModel = self.dataArr[btn.tag];
        NSNumber *meimgId = photoModel.meimgId;

        if (meimgId) {
            @weakify(self);
            [self showProgressView];
            [[[PigMarketApi sharedInstance] deletephotoWithMemberId:meimgId] subscribeNext:^(NSNull * _Nullable x) {
                @strongify(self);
                [self hideProgressView];
                [self.dataArr removeObject:photoModel];
                [kNotificationCenter postNotificationName:NotificationPhotoDeleteChange object:self userInfo:nil];
                [self.photoCollectionView reloadData];
                
            } error:^(NSError * _Nullable error) {
                @strongify(self);
                [self hideProgressView];
                [self handlingError:error];
            }];
        }
        
    }else{
        
        [self deleteLocalDataWithIndex:btn.tag - index];
    }

}


//删除本地照片数据
- (void)deleteLocalDataWithIndex:(NSInteger)index {
    
    if ([self collectionView:self.photoCollectionView numberOfItemsInSection:0] <= self.currentPhotos.count) {
        [self.currentPhotos removeObjectAtIndex:index];
        [self.currentAssets removeObjectAtIndex:index];
        [self.photoCollectionView reloadData];
        return;
    }
    
    [self.currentPhotos removeObjectAtIndex:index];
    [self.currentAssets removeObjectAtIndex:index];
    [self.photoCollectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
        [self->_photoCollectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self->_photoCollectionView reloadData];
    }];
}


- (void)longPressGestureTapped:(UILongPressGestureRecognizer *)tap {
    if (tap.state == UIGestureRecognizerStateBegan) {
        NSIndexPath *longIndexPath = [self.photoCollectionView indexPathForItemAtPoint:[_longPressGestureRecognizer locationInView:self.photoCollectionView]];
        // 找到当前的cell
        NSUInteger count = self.dataArr.count + self.currentPhotos.count;

        ModifyPhotoCell *cell = (ModifyPhotoCell *)[self.photoCollectionView cellForItemAtIndexPath:longIndexPath];
        if (longIndexPath.item < count) {
            cell.deleteBtn.hidden = NO;
            cell.isShaking = YES;
            [self startShakeView:cell];
        } else {
            cell.isShaking = NO;
        }
    }
}

#pragma mark - private method
//获取图片列表请求
- (void)requestAllPhotos {
    [self.dataArr removeAllObjects];
    NSNumber *memberID = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getPhotosWithMemberId:memberID] subscribeNext:^(PhotosList * _Nullable photoList) {
        @strongify(self);
        
        [self.dataArr addObjectsFromArray:photoList.imgList];
        [self.photoCollectionView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


//上传图片接口请求
- (void)uploadPhotosWithPhotos {
    
    [self showProgressView];
    NSString *account = [UserInfoDataProvider sharedInstance].userInfo.phone;
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] uploadPhotosWithPhotosArr:self.currentPhotos account:account type:UpDateImageType_Photo] subscribeNext:^(PhotosList * _Nullable photoList) {
        @strongify(self);
        [self hideProgressView];
        
        if ([self.title isEqualToString:CommonPhotoTitle]) {//上传图片后 上传imgName接口请求
            
            //个人资料上传图片imageName
            [kNotificationCenter postNotificationName:NotificationPhotosNameChanged object:self userInfo:@{@"photoNameModel":photoList.imgList}];
            [self.navigationController popViewControllerAnimated:YES];

        }else {//完善个人资料页照片   无需上传imgName接口请求
            
            //个人资料上传图片imageName
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationPhotosNameChanged object:self userInfo:@{@"photoNameModel":photoList.imgList}];
            [self.navigationController popViewControllerAnimated:YES];
            
        }
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self hideProgressView];
        [self handlingError:error];
    }];
}


/** 拍照 */
- (void)takePhoto {
   // AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
}


/** 相册 */
- (void)photoAlbum {
    
    NSInteger number = 6 - self.dataArr.count;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:number columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.selectedAssets = self.currentAssets; // 目前已经选中的图片数组
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


/** 抖动a动画 */
- (void)startShakeView:(UIView *)viewToShake {
    // 实例化
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
    // 拿到动画 key
    anim.keyPath =@"transform.rotation";
    // 动画时间
    anim.duration =.25;
    // 无限次重复
    anim.repeatCount = MAXFLOAT;
    // 设置抖动数值
    anim.values = @[@(ANGLE_TO_RADIAN(-5)),@(ANGLE_TO_RADIAN(5)),@(ANGLE_TO_RADIAN(-5))];
    // 保持最后的状态
    anim.removedOnCompletion = NO;
    // 动画的填充模式
    anim.fillMode = kCAFillModeForwards;
    // layer层实现动画
    [viewToShake.layer addAnimation:anim forKey:@"shake"];
}


/** 结束抖动动画 */
- (void)endShake:(UIView *)view {
    [view.layer removeAnimationForKey:@"shake"];
}


#pragma mark - getter and setter

- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] init];
        _topView.backgroundColor = [UIColor colorWithHexString:@"#fff9d4"];
    }
    return _topView;
}


- (UILabel *)tips {
    if (!_tips) {
        _tips = [[UILabel alloc] init];
        _tips.textColor = [UIColor colorWithHexString:@"#ec8c00"];
        _tips.font = [UIFont smallFont];
        _tips.text = @"常用照片最多可上传6张,长按可删除";
    }
    return _tips;
}


- (UICollectionView *)photoCollectionView {
    if (!_photoCollectionView) {
        _flowLayout = [[ModifyPhotoFlowLayout alloc] init];
        _photoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
        // 注册CollectionView的Cell
        [_photoCollectionView registerClass:[ModifyPhotoCell class] forCellWithReuseIdentifier:@"ModifyPhotoCellID"];
        _photoCollectionView.delegate = self;
        _photoCollectionView.dataSource = self;
        _photoCollectionView.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
    }
    return _photoCollectionView;
}

- (NSMutableArray *)currentPhotos {
    if (!_currentPhotos) {
        _currentPhotos = [NSMutableArray array];
    }
    return _currentPhotos;
}


- (NSMutableArray *)currentAssets {
    if (!_currentAssets) {
        _currentAssets = [NSMutableArray array];
    }
    return _currentAssets;
}


- (NSMutableArray *)uploadImgsNameArr {
    if (!_uploadImgsNameArr) {
        _uploadImgsNameArr = [[NSMutableArray alloc] init];
    }
    return _uploadImgsNameArr;
}


- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}


@end
